﻿using System;
using System.Data.SqlClient;
using sscore;
using sscore.Utils;

namespace DM4
{
    public partial class DM4
    {
        public XMLInfo GetUserList(string usrSessionId)
        {
            BeginFunction("GetUserList");

            OperationResult userIdOpResult = GetUserIdBySession(usrSessionId);
            XMLInfo xi = new XMLInfo(userIdOpResult);

            if (!userIdOpResult)
            {
                WriteLog(userIdOpResult.Message, MessageType.Error);
                return xi;
            }

            const string sql = "SELECT [usr_id],[usr_login]+'('+[usr_fullname]+')' as [usr_name] FROM [users]";
            WriteDebugLog(sql);

            try
            {
                SqlCommand sel = new SqlCommand(sql, _conn);
                using (SqlDataReader reader = sel.ExecuteReader())
                {
                    if (reader.HasRows)
                        try
                        {
                            WriteLog("Get user list for users table, operation complete");
                            xi.Load(reader, "users");
                        }

                        catch (Exception ex)
                        {
                            WriteLog(ex.Message, MessageType.Error);
                        }
                }
            }
            catch (Exception ex)
            {
                WriteLog(ex.Message, MessageType.Error);
            }

            EndFunction("GetUserList");
            return xi;
        }

        private UserInfo GetUserInfo(int id)
        {
            BeginFunction("GetUserInfo");

            string sql = String.Format("select [usr_id], [usr_login], [usr_password], [usr_email], [usr_fullname] , [usr_access_level] from users where usr_id = {0}", id);
            WriteDebugLog(sql);

            UserInfo ui = new UserInfo();

            SqlCommand sel = new SqlCommand(sql, _conn);
            using (SqlDataReader reader = sel.ExecuteReader())
            {
                try
                {
                    reader.Read();

                    ui.UsrId = SysUtils.ConvertFromDBVal<int>(reader["usr_id"]);
                    ui.UsrLogin = SysUtils.ConvertFromDBVal<string>(reader["usr_login"]);
                    ui.UsrPassword = SysUtils.ConvertFromDBVal<string>(reader["usr_password"]);
                    ui.UsrFullname = SysUtils.ConvertFromDBVal<string>(reader["usr_fullname"]);
                    ui.UsrEmail = SysUtils.ConvertFromDBVal<string>(reader["usr_email"]);
                    ui.UsrAccessLevel = (AccessLevel)SysUtils.ConvertFromDBVal<int>(reader["usr_access_level"]);

                }

                catch (Exception ex)
                {
                    WriteLog(ex.Message, MessageType.Error);
                }
            }

            EndFunction("GetUserInfo");

            return ui;
        }
    }
}
